﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Core;
using MvcEngine.Core.Repositories;

using MvcEngine.Core.Helpers;
using System.Diagnostics;

namespace MvcEngine.Mvc
{
    [AttributeUsage(AttributeTargets.Class)]
    public class ModulePermissionAttribute : ActionFilterAttribute
    {
        private string key = null;

        public ModulePermissionAttribute(string key)
        {
            this.key = key;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var ctrIdStr = filterContext.RouteData.Values["ctrId"];

            if (ctrIdStr == null)
            {
                string msg = string.Empty;

                foreach (var item in filterContext.RouteData.Values)
                {
                    msg += " key: " + item.Key + " value: " + item.Value.ToString() + " --";
                }

                LogHelper.Current.WriteError("ControlId is not present in routedata. " + msg);
            }

            int pageContentId = int.Parse(ctrIdStr.ToString());

            if (PermissionHelper.Current.HasRights(UserContext.Current.User, pageContentId, key))
                return;

            throw new ModulePermissionException("You don't have permissions.");
        }
    }
}
